package com.future.mayi.qsale.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.google.gson.reflect.TypeToken;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;
import com.future.mayi.R;
import com.future.mayi.activity.BaseTitleActivity;
import com.future.mayi.app.App;
import com.future.mayi.qsale.model.QsaleGoodsListModel;
import com.future.mayi.qsale.utils.SelectImgUtils;
import com.future.mayi.qsale.utils.UploadMutilImgUtils;
import com.future.mayi.qsale.widget.ConsignSaleItemLayout;
import com.future.mayi.utils.CompressImgUtils;
import com.future.mayi.utils.KefuUtils;
import com.future.mayi.utils.Navigator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 寄售
 * Created by Administrator on 2018/5/24.
 */

public class ConsignSaleActivity extends BaseTitleActivity implements ConsignSaleItemLayout.OnQSaleItemListener {

    private static final String TAG = "ConsignSaleActivity";

    public static final String EXTRA_IS_SALE = "extra_is_sale";


    private List<ConsignSaleItemLayout> editItemViewList;

    @BindView(R.id.iv_confirm)
    ImageView ivConfirm;
    @BindView(R.id.btn_order_to_sale)
    TextView btnOrderToSale;
    @BindView(R.id.ll_container)
    LinearLayout llContainer;
    @BindView(R.id.tv_add_item)
    TextView tvAddItem;
    @BindView(R.id.tv_sale_protocol)
    TextView tvSaleProtocol;

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_consign_sale);
    }

    @Override
    protected void initView() {
        addEditedItem();
//        tvSaleProtocol.setText(isConsignSale() ?
//                getResources().getString(R.string.confirm_sale_protocol) :
//                getResources().getString(R.string.confirm_recycle_protocol));

        btnOrderToSale.setText(isConsignSale() ? "预约寄卖" : "预约回收");
    }

    @Override
    protected void initDates() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("商品信息");
        getRightText().setText(isConsignSale() ? "寄卖流程" : "回收流程");
        getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigator.navigatorFlowIntroActivity(ConsignSaleActivity.this, !isConsignSale());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == SelectImgUtils.REQUEST_CODE_IMAGE) {
            final ArrayList<String> pathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            if (pathList != null && pathList.size() > 0 && (!TextUtils.isEmpty(pathList.get(0)))) {
                showLoadingDialog();
                CompressImgUtils compressImgUtils = new CompressImgUtils();
                compressImgUtils.compressImg(pathList, new CompressImgUtils.OnCompressImgListener() {
                    @Override
                    public void onSucceed(List<String> pathList) {
                        dissmissLoadingDialog();
                        getRecentEditLayout().addImg(pathList);
                    }

                    @Override
                    public void onFailed(Exception e) {
                        dissmissLoadingDialog();
                    }
                });
            }
        }
    }


    @OnClick({R.id.btn_order_to_sale, R.id.tv_add_item, R.id.tv_sale_protocol})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_order_to_sale:
                postOrders();
                break;
            case R.id.tv_add_item:
                addEditedItem();
                break;
            case R.id.tv_sale_protocol:
                KefuUtils.startActivity(this);
                break;
            default:
                break;
        }
    }

    /**
     * 发布预约信息
     */
    private void postOrders() {

        ArrayList<List<String>> imgLists = new ArrayList<>();
        final ArrayList<QsaleGoodsListModel> qsaleGoodsListModels = new ArrayList<>();

        for (int i = 0; i < editItemViewList.size(); i++) {
            ConsignSaleItemLayout consignSaleItemLayout = editItemViewList.get(i);

            if (consignSaleItemLayout.isEditedStatus()) {
                //editStatus
                if (consignSaleItemLayout.verifyInput()) {
                    imgLists.add(consignSaleItemLayout.getImgPath());
                    qsaleGoodsListModels.add(consignSaleItemLayout.getUploadModel());
                } else {
                    return;
                }
            } else {
                //completedStatus
                imgLists.add(consignSaleItemLayout.getImgPath());
                qsaleGoodsListModels.add(consignSaleItemLayout.getUploadModel());
            }

        }

        if (imgLists.size() > 0 && qsaleGoodsListModels.size() > 0
                && imgLists.size() == qsaleGoodsListModels.size()) {
            showLoadingDialog();
            UploadMutilImgUtils uploadMutilImgUtils = new UploadMutilImgUtils(this, new UploadMutilImgUtils.UploadListener() {
                @Override
                public void uploadSucceed(List<String> imgString) {
                    formatData(imgString, qsaleGoodsListModels);
                }

                @Override
                public void uploadFailed(String message) {
                    dissmissLoadingDialog();
                }
            });
            uploadMutilImgUtils.startUpload(imgLists);
        }
    }

    public void formatData(List<String> imgString, List<QsaleGoodsListModel> qsaleGoodsListModels) {
        if (imgString != null && imgString.size() == qsaleGoodsListModels.size()) {
            for (int i = 0; i < imgString.size(); i++) {
                qsaleGoodsListModels.get(i).setImg_list(imgString.get(i));
            }
            sendConsignRequest(qsaleGoodsListModels);
        } else {
            dissmissLoadingDialog();
            toast("上传失败!");
        }
    }

    public void sendConsignRequest(List<QsaleGoodsListModel> qsaleGoodsListModels) {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.addConsignorder)
                .addParam("token", App.getToken(this))
                .addParam("order_type", isConsignSale() ? 1 : 2)
                .addParam("goods_list", App.getGson().toJson(qsaleGoodsListModels, new TypeToken<List<QsaleGoodsListModel>>() {
                }.getType()))
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        String orderId = "";
                        try {
                            JSONObject object = new JSONObject(response.content);
                            orderId = object.optString("order_id");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        dissmissLoadingDialog();
                        toast(response.message);
                        Navigator.navigatorToSucceedConsignActivity(ConsignSaleActivity.this, orderId, isConsignSale() ? 1 : 2);
                        ConsignSaleActivity.this.finish();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        dissmissLoadingDialog();
                        toast(message);
                    }
                })
                .start(new DefaultResponse());
    }

    /**
     * 新建并增加
     */
    private void addEditedItem() {
        if (editItemViewList == null) {
            editItemViewList = new ArrayList<>();
        }

        if (savePreItem()) {
            ConsignSaleItemLayout consignSaleItemLayout = new ConsignSaleItemLayout(this);
            consignSaleItemLayout.setOnQsaleItemListener(ConsignSaleActivity.this);
            consignSaleItemLayout.setTag(R.id.item_layout_tag, System.currentTimeMillis());
            int index = editItemViewList.size();
            editItemViewList.add(index, consignSaleItemLayout);
            llContainer.addView(consignSaleItemLayout, index);
        }
    }

    /**
     * 保存正在编辑item的状态
     */
    private boolean savePreItem() {
        boolean isSaved = true;
        if (editItemViewList == null) return true;
        ConsignSaleItemLayout consignSaleItemLayout = getRecentEditLayout();
        if (consignSaleItemLayout != null) {
            isSaved = consignSaleItemLayout.completedStatus();
        }
        return isSaved;
    }

    /**
     * 正在编辑的item
     *
     * @return
     */
    public ConsignSaleItemLayout getRecentEditLayout() {
        if (editItemViewList == null || editItemViewList.size() == 0) return null;

        for (int i = 0; i < editItemViewList.size(); i++) {
            if (editItemViewList.get(i).isEditedStatus()) {
                return editItemViewList.get(i);
            }
        }
        return null;
    }

    /**
     * 根据Tag获取完成状态的Layout
     *
     * @param createTag
     * @return
     */
    public ConsignSaleItemLayout getCompletedLayout(long createTag) {
        if (editItemViewList == null || editItemViewList.size() == 0) return null;
        for (int i = 0; i < editItemViewList.size(); i++) {
            if (createTag == (Long) editItemViewList.get(i).getTag(R.id.item_layout_tag)) {
                return editItemViewList.get(i);
            }
        }
        return null;
    }


    @Override
    public void onSelectImgClick(int position, int maxItem) {
        SelectImgUtils selectImgUtils = new SelectImgUtils();
        if (selectImgUtils == null) {
            selectImgUtils = new SelectImgUtils();
        }
        selectImgUtils.selectImg(ConsignSaleActivity.this, maxItem);
    }

    @Override
    public void onDeleteClick() {
        if (editItemViewList == null || editItemViewList.size() < 2) {
            toast("无法继续删除");
            return;
        }

        ConsignSaleItemLayout consignSaleItemLayout = getRecentEditLayout();
        editItemViewList.remove(consignSaleItemLayout);
        llContainer.removeView(consignSaleItemLayout);
    }


    @Override
    public void showWaitingDialog() {
        showLoadingDialog();
    }

    @Override
    public void dismissWaitingDialog() {
        dissmissLoadingDialog();
    }

    @Override
    public void showEditDetail(long layoutCreateTag) {
        if (getRecentEditLayout() != null) {
            if (getRecentEditLayout().completedStatus()) {
                ConsignSaleItemLayout consignSaleItemLayout = getCompletedLayout(layoutCreateTag);
                if (consignSaleItemLayout != null) {
                    consignSaleItemLayout.editStatus();
                }
            }
        } else {
            ConsignSaleItemLayout consignSaleItemLayout = getCompletedLayout(layoutCreateTag);
            if (consignSaleItemLayout != null) {
                consignSaleItemLayout.editStatus();
            }
        }
    }


    private Boolean ISSALE;

    /**
     * 是否是寄卖而不是回收
     *
     * @return
     */
    private boolean isConsignSale() {
        if (ISSALE == null) {
            ISSALE = getIntent().getBooleanExtra(EXTRA_IS_SALE, true);
        }
        return ISSALE;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
